var grid, store, dialog, editing, userEditForm, bankcardGrid, bankcardStore;
var isAdd = false;
$(function () {
    init();
    initCombo();
});
function initCombo() {
    var data = [{id: 'M', name: '现金收益'}, {id: 'E', name: 'ETH收益'}]
    CommonClass.setComboData($('#revenueType'), data, "id", "name");
}
function init() {

    var Grid = BUI.Grid,
        Store = BUI.Data.Store,
        columns = [
            {title: '用户ID', width: 100, sortable: true, dataIndex: 'id', selectable: true},
            {title: '用户名', width: 100, sortable: false, dataIndex: 'userName'},
            {title: '手机号', width: 100, sortable: true, dataIndex: 'phoneNumber', selectable: true},
            {title: '身份证号', width: 100, sortable: true, dataIndex: 'identityCard', showTip: true},
            {title: '总余额', width: 100, sortable: true, dataIndex: 'balance'},
            {title: '冻结金额', width: 100, sortable: true, dataIndex: 'frozeMoney'},
            {title: 'ETH余额', width: 100, sortable: true, dataIndex: 'ethBalance'},
            {title: 'ETH冻结', width: 100, sortable: true, dataIndex: 'ethFrozeMoney'},
            {
                title: '收益类型', width: 100, sortable: true, dataIndex: 'revenueType', renderer: function (value) {
                    if(value=="M"){
                        return "现金收益"
                    }else{
                        return "ETH收益"
                    }
            }
            },
            {title: '电费', width: 100, sortable: true, dataIndex: 'electricityFee'},
            {title: '冻结算力', width: 100, sortable: true, dataIndex: 'frozenComputingPower'},
            {title: '有效算力', width: 100, sortable: true, dataIndex: 'computingPower'},
            {title: '银行卡信息', width: 100, sortable: true, dataIndex: 'bankInfo'},
            {title: '创建时间', width: 100, sortable: true, dataIndex: 'createTime'}
        ];

    store = new Store({
        url: ctx + '/user/admin/selectPageInfo',
        autoLoad: true,
        root: 'list',               //存放数据的字段名(rows)
        totalProperty: 'total',
        pageSize: 10
    });
    editing = new Grid.Plugins.CellEditing();
    var bankColumns = [
        {title: 'id', dataIndex: 'id', width: 100, visible: false},
        {title: 'userId', dataIndex: 'userId', width: 100, visible: false},
        {title: '银行名称', dataIndex: 'bankName', width: 100, editor: {xtype: 'text', rules: {required: true}}},
        {title: '卡号', dataIndex: 'carNo', width: 180, editor: {xtype: 'number', rules: {required: true}}}
    ];
    bankcardStore = new Store({
        data: [],
        autoLoad: true
    });
    bankcardGrid = new Grid.Grid({
        render: '#bankCarGrid',
        loadMask: true,
        height: 200,
        forceFit: true,
        columns: bankColumns,
        store: bankcardStore,
        plugins: [editing, Grid.Plugins.CheckSelection],
        // 底部工具栏
        tbar: {
            items: [{
                btnCls: 'button button-primary button-small',
                text: '新增',
                handler: addBankCar
            }, {
                btnCls: 'button button-primary button-small',
                text: '删除',
                handler: deleteBankCar
            }]
        }
    });
    grid = new Grid.Grid({
        render: '#grid',
        loadMask: true,
        forceFit: true,
        columns: columns,
        store: store,
        plugins: [Grid.Plugins.CheckSelection, Grid.Plugins.AutoFit], //勾选插件、自适应宽度插件
        // 底部工具栏
        tbar: {
            items: [{
                btnCls: 'button button-primary button-small',
                text: '新增',
                handler: addUser
            }, {
                btnCls: 'button button-primary button-small',
                text: '修改',
                handler: editUser
            }, {
                btnCls: 'button button-primary button-small',
                text: '删除',
                handler: deleteUser
            }]
        },
        // 顶部工具栏
        bbar: {
            //items 也可以在此配置
            // pagingBar:表明包含分页栏
            pagingBar: true
        }
    });
    grid.render();

    //创建表单，表单中的日历，不需要单独初始化
    var form = new BUI.Form.HForm({
        srcNode: '#searchForm'
    }).render();

    form.on('beforesubmit', function (ev) {
        //序列化成对象
        var obj = form.serializeToObject();
        obj.start = 0; //返回第一页
        store.load(obj);
        return false;
    });
    userEditForm = Bui.formRender("userEditForm");
    dialog = Bui.overlay({
        id: 'dialog',
        title: '修改用户信息',
        width: 400,
        height: 350,
        //配置DOM容器的编号
        contentId: 'content',
        buttons: [
            {
                text: '保存',
                elCls: 'button button-primary',
                handler: function () {
                    // if (!userEditForm.isValid()) {
                    //     return;
                    // }
                    var result = bankcardStore.getResult();

                    var formVal = CommonClass.getForm("userEditForm");
                    if (formVal.password != undefined && formVal.password != null && formVal.password.trim() != "") {
                        formVal.password = $.md5(formVal.password)
                    } else {
                        formVal.password = null
                    }
                    if (!isAdd) {
                        formVal.id = grid.getSelection()[0].id;
                    }

                    var bankcards = [];
                    for (var i = 0; i < result.length; i++) {
                        if (result[i].bankName == null || result[i].bankName == '') {
                            return BUI.Message.Alert('第' + (i + 1) + '条 银行名称不能为空', function () {
                            }, 'warning');
                        }
                        if (result[i].carNo == null || result[i].carNo == '') {
                            return BUI.Message.Alert('第' + (i + 1) + '条 卡号不能为空', function () {
                            }, 'warning');
                        }
                        bankcards.push(result[i])
                    }
                    formAction({
                        userStr: JSON.stringify(formVal),
                        bankcards: JSON.stringify(bankcards)
                    }, ctx + '/user/admin/updateUser')

                }
            }, {
                text: '关闭',
                elCls: 'button',
                handler: function () {
                    this.close();
                }
            }
        ]
    });
    dialog.addChild(bankcardGrid)

}

function deleteBankCar() {
    var selections = bankcardGrid.getSelection();
    bankcardStore.remove(selections);
}

function addBankCar() {
    var newData = {bankName: '', carNo: '', id: -1, userId: 1};
    bankcardStore.add(newData);
    editing.edit(newData, 'bankName'); //添加记录后，直接编辑

}

function addUser() {
    isAdd = true;
    $(".frozenComputingPower").attr("disabled", true);
    $(".computingPower").attr("disabled", true);
    dialog.set("title", "新增用户信息");
    document.getElementById("userEditForm").reset();
    CommonClass.fieldVaild();
    dialog.show();
}

function editUser() {
    isAdd = false;
    var selections = grid.getSelection();
    if (selections.length == 0) {
        BUI.Message.Alert('请选择一条记录！', function () {
        }, 'info');
        return;
    }
    if (selections.length > 1) {
        BUI.Message.Alert('只能选择一条记录！', function () {
        }, 'info');
        return;
    }
    $.ajax({
        type: 'POST',
        url: ctx + "/user/admin/selectUserById",
        data: {id: selections[0].id},
        success: function (data) {
            if (data.success) {
                $(".frozenComputingPower").attr("disabled", false);
                $(".computingPower").attr("disabled", false);
                document.getElementById("userEditForm").reset();
                CommonClass.setForm('userEditForm', data.user);
                $(".frozenComputingPower").attr("disabled", true);
                $(".computingPower").attr("disabled", true);
                bankcardStore.load();
                bankcardStore.add(data.bankCards);
                dialog.show();
            } else {
                BUI.Message.Alert(data.errorMessage, 'error');
            }

        }
    });

}

function deleteUser() {
    CommonClass.deleteGridData(grid, store, ctx + "/user/admin/deleteUser");

}

function formAction(formVal, actionUrl) {
    CommonClass.AjaxAction(actionUrl, formVal, function (data) {
        if (data.success) {
            Message.show(data.msg, "success", 2000);
            store.load()
            dialog.close();
        } else {
            Message.show(data.msg, "error", 2000);
        }
    });
}